package file.login;

import file.Constant;
import file.config.FsConfig;
import file.config.MyConfigProperties;
import file.util.FileUtil;
import file.util.SHA256Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * @author hh
 * @since 2024/12/7
 */
@Controller
public class LoginController {

    private final Logger log = LoggerFactory.getLogger(LoginController.class);

    private final MyConfigProperties myConfigProperties;

    public LoginController(MyConfigProperties myConfigProperties) {
        this.myConfigProperties = myConfigProperties;
    }

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @RequestMapping("/console")
    public String index() {
        return "main";
    }

    @PostMapping("/doLogin")
    @ResponseBody
    public String doLogin(@RequestParam String pwd) {
        if (!StringUtils.hasText(pwd)) {
            return "0";
        }
        try {
            if (SHA256Util.validatePwd(pwd)) {
                String token = TokenManager.generateToken();
                TokenManager.cacheToken(token);
                return token;
            }
            return "0";
        } catch (Exception e) {
            log.error("登录失败", e);
            return "0";
        }
    }

    @PostMapping("/updatePwd")
    @ResponseBody
    public String updatePwd(String oldPwd, String newPwd) {
        try {
            String oldPwdContent = FsConfig.get(Constant.PWD);
            String encrypt = SHA256Util.encrypt(oldPwd);
            // 旧密码校验失败
            if (!Objects.equals(oldPwdContent, encrypt)) {
                return "1";
            }

            FileUtil.saveFile(SHA256Util.encrypt(newPwd), FileUtil.getRealPath(myConfigProperties.getFilePath()) + FsConfig.CONFIG_FILE_NAME);
            return "0";
        } catch (Exception e) {
            log.error("修改密码失败", e);
            return "1";
        }
    }

}
